<?php
require_once 'models/organization/organization.php';
/**
 * Хендлер для получения справочника оргструктуры
 **/ 
class GetCompanyOrganization extends WallrideHandler{

  protected
    $companyId = false;

	public function setParams($params){  
    if (!empty($params['companyObj']) && !empty($params['companyObj']->data['company_id']))
        $this->companyId = $params['companyObj']->data['company_id'];
    
	}

	public function process(){
    if (!$this->companyId) return false;

    // получаем ассоциированный массив подразделений
    $org = OrganizationModel::getByCompanyIdAsDictionary($this->companyId);
    foreach ($org as $key=>$obj){
      $org[$key]->data['ext_parent_ids'] = $this->getParentIds($org, $key);
      $org[$key]->data['ext_children_ids'] = $this->getChildrenIds($org, $key);
      $org[$key]->data['ext_1st_level_children_ids'] = $this->get1stLevelChildrenIds($org, $key);
    }
    return $org;
	}

  /**
   * Достаём все ID вышестоящих объектов
   * @param <type> $objects
   * @param <type> $currentId
   * @return <type> 
   */
  private function getParentIds(&$objects, $currentId){
    $res = array();
    $parentId = $objects[$currentId]->data['parent_id'];
    if (!empty($parentId)){
      $res = $this->getParentIds($objects, $parentId);
      $res[] = $parentId;
    }
    return $res;
  }

  /**
   * Достаём ID всех дочерних объектов
   * @param <type> $objects
   * @param <type> $currentId
   * @return <type> 
   */
  private function getChildrenIds(&$objects, $currentId){
    $res = array();
    foreach ($objects as $key=>$obj){
      if ($obj->data['parent_id']==$currentId){
        $res[] = $key;
        $res = array_merge($res, $this->getChildrenIds($objects, $key));
      }
    }
    return $res;
  }

  /**
   * Достаём ID "детей" 1 уровня.
   * @param <type> $objects
   * @param <type> $currentId
   * @return <type>
   */
  private function get1stLevelChildrenIds(&$objects, $currentId){
    $res = array();
    foreach ($objects as $key=>$obj){
      if ($obj->data['parent_id']==$currentId){
        $res[] = $key;
      }
    }
    return $res;
  }
}
?>
